package net.huashitong.zhApp.controller;

import com.sirdc.modules.utils.ObjectUtils;
import com.sirdc.modules.utils.StringUtils;
import jodd.util.StringUtil;
import net.huashitong.log.service.LogMessageService;
import net.huashitong.node.entity.NodeNewtemplet;
import net.huashitong.node.filter.NodeNewtempletFilter;
import net.huashitong.node.service.NodeNewtempletService;
import net.huashitong.user.databean.BnpUserDatabean;
import net.huashitong.user.entity.BnpUser;
import net.huashitong.user.filter.BnpUserFilter;
import net.huashitong.user.service.BnpUserService;
import net.huashitong.zhApp.service.AppManagerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import static net.huashitong.utils.UtilsTools.getClientIp;

@Controller
@RequestMapping(value = "/zhApp/manager")
public class AppManagerController extends BaseCtrl {

    @Autowired
    private BnpUserService bnpUserService;
    @Autowired
    private AppManagerService appManagerService;
    @Autowired
    private NodeNewtempletService nodeNewtempletService;
    @Lazy
    @Autowired
    private LogMessageService logMessageService;


    //=======================================用户管理=======================================
    /**
     * 查询部门（分为业主单位0、审批部门1、督查组4、分管领导6、主要领导7）branchType
     * userPhone
     * "paging":{"currentPage":1}
     * <p>
     * 也可以进行模糊搜索单位，或配合branchType组合搜索
     * searchWord
     *
     * @param filter
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/deptList", method = RequestMethod.POST)
    public Map<String, Object> queryDeptList(@RequestBody BnpUserFilter filter) {
        BnpUser user = queryUserAuth(filter.getUserPhone());
        if (ObjectUtils.isBlank(user)) {
            return coverMessage("202", "无用户权限");
        } else {
            //默认查询业主单位部门信息
            List<BnpUser> list = bnpUserService.queryBranchsByType(filter);
            for (BnpUser bnpUser : list) {
                bnpUser.setPhone(null);
                bnpUser.setRole(null);
                bnpUser.setPassword(null);
                bnpUser.setName(null);
                bnpUser.setSysId(null);
            }
            return coverMessage("200", "获取成功", list);
        }
    }


    /**
     * 根据部门名称查询用户列表
     * branch 部门名称
     * <p>
     * 也可以进行模糊搜索单位，或配合branchType组合搜索
     * searchWord
     *
     * @param filter
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/queryUsersListByBranch", method = RequestMethod.POST)
    public Map<String, Object> queryUsersListByBranch(@RequestBody BnpUserFilter filter) {
        BnpUser user = queryUserAuth(filter.getUserPhone());
        if (ObjectUtils.isBlank(user)) {
            return coverMessage("202", "无用户权限");
        } else {
            List<BnpUser> list = bnpUserService.getUserInfoUsePage(filter);
            return coverMessage("200", "获取成功", list);
        }
    }

    /**
     * 获取所有单位
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/getBranchInAllUser", method = RequestMethod.GET)
    public Map<String, Object> getBranchInAllUser() {
        List<String> branchs = bnpUserService.getBranchInAllUser();
        return coverMessage("200", "获取成功", branchs);
    }

    /**
     * 更新用户操作
     *
     * @param filter
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/updateUsers", method = RequestMethod.POST)
    public Map<String, Object> updateUsers(@RequestBody BnpUserFilter filter, HttpServletRequest request) {
        BnpUser user = queryUserAuth(filter.getUserPhone());
        if (ObjectUtils.isBlank(user)) {
            return coverMessage("202", "无用户权限");
        } else {
            //查询原来的用户信息
            BnpUser user1 = bnpUserService.getById(filter.getSysid());
            String ip = getClientIp(request);
            if (StringUtils.isNotBlank(filter.getPhone())) {
                BnpUserFilter bnpUserFilter = new BnpUserFilter();
                bnpUserFilter.setPhone(filter.getPhone());
                List<BnpUser> userList = bnpUserService.queryByFilter(bnpUserFilter);
                if (ObjectUtils.isNotBlank(userList)) {
                    if(!user1.getName().equals(userList.get(0).getName())){
                        return coverMessage("202", "系统已经存在该手机号，故验证不通过！");
                    }
                }
                filter.setIP(ip);
                //更新节点清单表
                appManagerService.updateUserInNodeNewSchedules(user, user1, filter);
                //更新督查任务表
                appManagerService.updateUserInSupervisionTask(user, user1,filter);
                //更新项目表
                appManagerService.updateUserInProject(user, user1,filter);
                //更新用户表手机号
                logMessageService.saveLogMessage(
                        user.getSysId(),
                        ip,
                        "userId:" + user1.getSysId(),
                        "修改",
                        "t_bnp_user",
                        "修改用户手机号",
                        user1.getPhone(),
                        filter.getPhone()
                );
                user1.setPhone(filter.getPhone());

            }
            if (StringUtils.isNotBlank(filter.getBranchType())) {
                //更新用户表单位类型
                logMessageService.saveLogMessage(
                        user.getSysId(),
                        ip,
                        "userId:" + user1.getSysId(),
                        "修改",
                        "t_bnp_user",
                        "修改用户单位类型",
                        user1.getBranchType(),
                        filter.getBranchType()
                );
                user1.setBranchType(filter.getBranchType());
            }
            if (StringUtils.isNotBlank(filter.getBranch())) {
                //更新用户表单位
                logMessageService.saveLogMessage(
                        user.getSysId(),
                        ip,
                        "userId:" + user1.getSysId(),
                        "修改",
                        "t_bnp_user",
                        "修改用户单位",
                        user1.getBranch(),
                        filter.getBranch()
                );
                user1.setBranch(filter.getBranch());
            }
            if (StringUtils.isNotBlank(filter.getRole())) {
                //更新用户表用户角色
                logMessageService.saveLogMessage(
                        user.getSysId(),
                        ip,
                        "userId:" + user1.getSysId(),
                        "修改",
                        "t_bnp_user",
                        "修改用户单位",
                        user1.getRole(),
                        filter.getRole()
                );
                user1.setRole(filter.getRole());
            }
            bnpUserService.update(user1);
            return coverMessage("200", "用户更新成功");
        }
    }

    //=======================================模板管理=======================================

    /**
     *  查询模板信息
     *  1 企业投资类
     *  2 土地收储类
     *  3 政府投资房建市政类
     *  4 政府投资交通水利类
     *
     * @param filter
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/queryTemplateList", method = RequestMethod.POST)
    public Map<String, Object> queryTemplateList(@RequestBody NodeNewtempletFilter filter) {
        List<NodeNewtemplet> list = nodeNewtempletService.getNodeTempletInfo(filter);
        List<Map<String,String>> mapList = new ArrayList<>();
        for (NodeNewtemplet nodeNewtemplet : list) {
            Map<String,String> map = new TreeMap<>();
            map.put("sysId", nodeNewtemplet.getSysId());
            map.put("nodeId", nodeNewtemplet.getNodeId());
            map.put("nodeName", nodeNewtemplet.getNodeName());
            map.put("nodeIds", nodeNewtemplet.getNodeIds());
            map.put("nodeIds", nodeNewtemplet.getNodeIds());
            map.put("planTime", nodeNewtemplet.getPlanTime());
            if(StringUtils.isBlank(nodeNewtemplet.getResUser())){
                map.put("resUser", "-");
            }else{
                map.put("resUser", nodeNewtemplet.getResUser());
            }
            if(StringUtils.isBlank(nodeNewtemplet.getOperatorUser())){
                map.put("operator", "-");
            }else{
                map.put("operator", nodeNewtemplet.getOperatorUser());
            }
            mapList.add(map);
        }
        return coverMessage("200", "获取模板信息成功",mapList);
    }

    /**
     * 根据sysId查询指定模板节点
     * @param filter
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/queryTemplateBySysId", method = RequestMethod.POST)
    public Map<String, Object> queryTemplateBySysId(@RequestBody NodeNewtempletFilter filter) {
        NodeNewtemplet nodeNewtemplet = nodeNewtempletService.getById(filter.getSysId());
        return coverMessage("200", "根据sysId查询指定模板节点成功",nodeNewtemplet);
    }

    /**
     * 修改指定模板节点
     * @param filter
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/editTemplateBySysId", method = RequestMethod.POST)
    public Map<String, Object> editTemplateBySysId(@RequestBody NodeNewtempletFilter filter, HttpServletRequest request) {
        String ip = getClientIp(request);
        BnpUser user = queryUserAuth(filter.getUserPhone());
        if (ObjectUtils.isBlank(user)) {
            return coverMessage("202", "无用户权限");
        } else {
            NodeNewtemplet nodeNewtemplet = nodeNewtempletService.getById(filter.getSysId());
            if(StringUtil.isNotBlank(filter.getPreNodeId())){
                nodeNewtemplet.setPreNodeId(filter.getPreNodeId());
                logMessageService.saveLogMessage(
                        user.getSysId(),
                        ip,
                        "sysId:" + filter.getSysId(),
                        "修改",
                        "t_bnp_node_newtemplet",
                        "修改前置节点",
                        nodeNewtemplet.getPreNodeId(),
                        filter.getPreNodeId()
                );
            }
            if(StringUtil.isNotBlank(filter.getNodeName())){
                nodeNewtemplet.setNodeName(filter.getNodeName());
                logMessageService.saveLogMessage(
                        user.getSysId(),
                        ip,
                        "sysId:" + filter.getSysId(),
                        "修改",
                        "t_bnp_node_newtemplet",
                        "修改节点名称",
                        nodeNewtemplet.getNodeName(),
                        filter.getNodeName()
                );
            }
            if(StringUtil.isNotBlank(filter.getPlanTime())){
                nodeNewtemplet.setPlanTime(filter.getPlanTime());
                logMessageService.saveLogMessage(
                        user.getSysId(),
                        ip,
                        "sysId:" + filter.getSysId(),
                        "修改",
                        "t_bnp_node_newtemplet",
                        "修改计划用时",
                        nodeNewtemplet.getPlanTime(),
                        filter.getPlanTime()
                );
            }
            nodeNewtempletService.update(nodeNewtemplet);
            return coverMessage("200", "修改指定模板节点" );
        }

    }
}
